/*
 * MessageFileJFrame.java
 *
 * Created on October 14, 2008, 12:52 PM
 */
package diagapplet;

import diagapplet.CodeGen.STI_TokenizerInterface;
import diagapplet.CodeGen.StructureTypeInfo;
import java.io.File;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import rcs.nml.NMLMessageDictionary;

/**
 *
 * @author  Will Shackleford
 */
public class MessageFileJFrame extends javax.swing.JFrame {

	/** Creates new form MessageFileJFrame */
	public MessageFileJFrame() {
		initComponents();
		if (null == other_frames) {
			other_frames = new Vector<JFrame>();
			other_frames.add(this);
		}
		this.watchJPanel1.setEditable(true);
	}

	public void LoadPackedFile(File f) {
		this.watchJPanel1.LoadPackedFile(f);
	}

	public void LoadXMLFile(File f) {
		this.watchJPanel1.LoadXMLFile(f);
	}

	public void setNmlMessageDictionary(NMLMessageDictionary _nml_dict) {
		this.watchJPanel1.setNmlMessageDictionary(_nml_dict);
	}

	/** This method is called from within the constructor to
	 * initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is
	 * always regenerated by the Form Editor.
	 */
	@SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        watchJPanel1 = new diagapplet.utils.WatchJPanel();
        jButtonPlotSelectedArray = new javax.swing.JButton();
        jTextFieldMessageType = new javax.swing.JTextField();
        jMenuBar1 = new javax.swing.JMenuBar();
        jMenu1 = new javax.swing.JMenu();
        jMenuPackedFileOpen = new javax.swing.JMenu();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jButtonPlotSelectedArray.setText("Plot Selected Array");
        jButtonPlotSelectedArray.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPlotSelectedArrayActionPerformed(evt);
            }
        });

        jTextFieldMessageType.setEditable(false);

        jMenu1.setText("File");

        jMenuPackedFileOpen.setMnemonic('o');
        jMenuPackedFileOpen.setText("Open Packed Message File ...");
        jMenuPackedFileOpen.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuPackedFileOpenActionPerformed(evt);
            }
        });
        jMenu1.add(jMenuPackedFileOpen);

        jMenuBar1.add(jMenu1);

        setJMenuBar(jMenuBar1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(watchJPanel1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(jButtonPlotSelectedArray, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldMessageType, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTextFieldMessageType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(watchJPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButtonPlotSelectedArray)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonPlotSelectedArrayActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPlotSelectedArrayActionPerformed
	StructureTypeInfo sti = this.watchJPanel1.getStructureTypeInfo();

	STI_TokenizerInterface stiti = sti.getInfoTokenizer();
	int var_number = this.watchJPanel1.GetVarNum();
	if (var_number < 1) {
		JOptionPane.showMessageDialog(this, "Please select array to plot first.");
		return;
	}
	String variable_name = this.watchJPanel1.GetVarName();
	int index = variable_name.indexOf('=');
	if (index > 0) {
		variable_name = variable_name.substring(0, index);
	}
	index = variable_name.lastIndexOf(' ');
	if (index > 0) {
		variable_name = variable_name.substring(index + 1);
	}
	index = variable_name.indexOf('[');
	if (index < 1) {
		JOptionPane.showMessageDialog(this, "\"" + variable_name + "\" does not appear to be an array.");
		return;
	}
	String slen_var = variable_name.substring(0, index) + "_length";
	while (index > 0) {
		int index2 = variable_name.indexOf(']', index);
		if (index2 < 0) {
			break;
		}
		variable_name = variable_name.substring(0, index) + "[]" + variable_name.substring(index2 + 1);
		index = variable_name.indexOf('[', index + 1);
	}
	int ndla_length_var_num = -1;
	int ndla_length = -1;
	int skip_size = 1;
	boolean second_found = false;
	int min_var_num = -1;
	int max_var_num = -1;
	boolean first_found = false;
	boolean ndla = false;
        boolean nula = false;

	int i = -1;
	while (stiti.hasMoreTokens()) {
		i++;
		String s = stiti.nextToken();
		if (s.indexOf(slen_var) >= 0) {
			ndla_length_var_num = i;
			ndla_length = Integer.valueOf(this.watchJPanel1.getValueStringForVarNumber(ndla_length_var_num)).intValue();
		}

		if (second_found && skip_size > 1 &&
				((i - min_var_num) % skip_size) != 0) {
			continue;
		}
		index = s.indexOf('[');
		while (index > 0) {
			int index2 = s.indexOf(']', index);
			if (index2 < 0) {
				break;
			}
			s = s.substring(0, index) + "[]" + s.substring(index2 + 1);
			index = s.indexOf('[', index + 1);
		}
		int spc_index;
		String orig_s = s;
		spc_index = s.lastIndexOf(' ');
		if (spc_index > 0) {
			s = s.substring(spc_index);
			s = s.trim();
		}
		if (s.equals(variable_name)) {
			if (!first_found) {
				first_found = true;
				if (orig_s.indexOf("NML_DYNAMIC_LENGTH_ARRAY") >= 0) {
					ndla = true;
				}
                                if (orig_s.indexOf("NML_UNBOUNDED_LENGTH_ARRAY") >= 0) {
					nula = true;
				}
				min_var_num = i;
			} else if (!second_found) {
				second_found = true;
				skip_size = i - min_var_num;
			} else if (ndla && ndla_length <= (i - min_var_num) / skip_size) {
				break;
			} else if (nula && ndla_length <= (i - min_var_num) / skip_size) {
				break;
			}
			max_var_num = i;
		} else if (second_found) {
			max_var_num = i;
			break;
		}

	}
	int len = (max_var_num - min_var_num);
	if (skip_size > 1) {
		len = (max_var_num - min_var_num) / skip_size + 1;
	}
	float xA[] = new float[len];
	float yA[] = new float[len];
	for (i = 0; i < yA.length; i++) {
		int var_index = i * skip_size + min_var_num;
		xA[i] = (float) i;
		yA[i] = Float.valueOf(this.watchJPanel1.getValueStringForVarNumber(var_index)).floatValue();
	}
	diagapplet.plotter.plotterJFrame plotter_frame = new diagapplet.plotter.plotterJFrame();
	plotter_frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
	plotter_frame.setVisible(true);
	plotter_frame.LoadXYFloatArrays(variable_name, xA, yA);
	if (null == other_frames) {
		other_frames = new Vector<JFrame>();
		other_frames.add(plotter_frame);
	}
}//GEN-LAST:event_jButtonPlotSelectedArrayActionPerformed

private void jMenuPackedFileOpenActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuPackedFileOpenActionPerformed
}//GEN-LAST:event_jMenuPackedFileOpenActionPerformed
	public JFrame parent;
	private static Vector<JFrame> other_frames = null;

private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
	if (parent != null && parent.getExtendedState() == JFrame.ICONIFIED) {
		if (null == other_frames) {
			for (JFrame f : other_frames) {
				if (f.isVisible() && f.getExtendedState() == JFrame.NORMAL) {
					return;
				}
			}
		}
		System.exit(0);
	}
}//GEN-LAST:event_formWindowClosed


	public void set_hashtable_by_id(Hashtable _hashtable_by_id) {
		this.watchJPanel1.set_hashtable_by_id(_hashtable_by_id);
	}

	public void SetTypeInfo(StructureTypeInfo _sti, Hashtable _ht) {
		try {
			this.watchJPanel1.SetTypeInfo(_sti, _ht);
			if (null != _sti) {
				this.jTextFieldMessageType.setText(_sti.Name);
			}
		} catch (Exception e) {
		}
	}

	public void SetDataInfo(Enumeration e) {
		this.watchJPanel1.SetDataInfo(e);
	}

	public void LoadDataStringFile(final File f) {
		this.watchJPanel1.LoadDataStringFile(f);
	}

	public void LoadDataStringFile(final String fileName) {
		this.LoadDataStringFile(new File(fileName));
	}

	/**
	 * @param args the command line arguments
	 */
	public static void main(final String args[]) {
		java.awt.EventQueue.invokeLater(new Runnable() {

			public void run() {
				MessageFileJFrame mfjf = new MessageFileJFrame();
				mfjf.setVisible(true);
				for (int i = 0; i < (args.length - 1); i++) {
					if (args[i].equalsIgnoreCase("--DataStringFile")) {
						mfjf.LoadDataStringFile(args[i + 1]);
					}
				}
			}
		});
	}

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonPlotSelectedArray;
    private javax.swing.JMenu jMenu1;
    private javax.swing.JMenuBar jMenuBar1;
    private javax.swing.JMenu jMenuPackedFileOpen;
    private javax.swing.JTextField jTextFieldMessageType;
    private diagapplet.utils.WatchJPanel watchJPanel1;
    // End of variables declaration//GEN-END:variables
}
